package com.udata.server.dao.impl;

import javax.jdo.PersistenceManager;

import com.google.appengine.api.datastore.Key;
import com.udata.server.dao.UserProfileDao;
import com.udata.server.model.UserProfile;
import com.udata.server.util.PMF;
import com.udata.shared.exception.OperationException;
import com.udata.shared.model.UserProfileB;

public class UserProfileDaoImpl extends UserProfileDao {

	@Override
	public UserProfileB saveUserProfile(UserProfileB userProfileB)
			throws OperationException {
		try {

			PersistenceManager pm = PMF.get().getPersistenceManager();
			try {
				UserProfile userProfile = null;
				if (userProfileB.getKey() != null) {
					userProfile = pm.getObjectById(UserProfile.class,
							userProfileB.getKey());
					userProfile.update(userProfileB);
				} else {
					userProfile = new UserProfile(userProfileB);

					userProfile = pm.makePersistent(userProfile);
				}
				userProfileB = userProfile.getBean();
				return userProfileB;
			} finally {
				pm.close();
			}
		} catch (Exception e) {
			throw new OperationException(this.getClass().getCanonicalName()
					+ ".saveUser\n" + e.getMessage());
		}
	}

	@Override
	public UserProfileB getUserProfile(Key key) throws OperationException {
		try {

			PersistenceManager pm = PMF.get().getPersistenceManager();
			try {
				UserProfileB userProfile = pm.getObjectById(UserProfileB.class,
						key);
				return userProfile;
			} finally {
				pm.close();
			}
		} catch (Exception e) {
			throw new OperationException(this.getClass().getCanonicalName()
					+ ".saveUser\n" + e.getMessage());
		}
	}

}
